/*
 * The MIT License 
 *
 * Copyright (c) 2010 pf-miles
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package me.wenyue.jclassview.binview.part;

import me.wenyue.jclassview.util.Constants;

/**
 * part of Hex table, presents addresses (hex addresses which always starts from
 * 0, it's the beginning of the file data, not the real address in memory or any
 * storages)
 * 
 * @author pf-miles 2010-11-16 下午08:19:04
 * 
 */
public class AddressTable {
    private int lines;

    public AddressTable(int lengthOfData) {
        if (lengthOfData % 16 == 0) {
            this.lines = lengthOfData / 16;
        } else {
            this.lines = lengthOfData / 16 + 1;
        }
    }

    public String toString() {
        int curStartAddress = 0x00000000;
        StringBuilder sb = new StringBuilder("<table border=\"1\" width=\"100%\" bordercolor=\"#D45D22\" style=\"font-family: monospace\">")
                .append(Constants.NEW_LINE);
        for (int i = 0; i < this.lines; i++) {
            curStartAddress += i * 16;
            sb.append("<tr>").append(Constants.NEW_LINE);
            sb.append("<td>").append(formatHex(curStartAddress)).append("</td>").append(Constants.NEW_LINE);
            sb.append("</tr>").append(Constants.NEW_LINE);
        }
        sb.append("</table>").append(Constants.NEW_LINE);
        return sb.toString();
    }

    private String formatHex(int curStartAddress) {
        String hex = Integer.toHexString(curStartAddress).toUpperCase();
        StringBuilder sb = new StringBuilder("0x");
        int precZs = 8 - hex.length();
        if (precZs > 0) {
            for (int i = 0; i < precZs; i++) {
                sb.append('0');
            }
        }
        sb.append(hex);
        return sb.toString();
    }

    // public static void main(String... args) {
    // System.out.println(new AddressTable(500));
    // }
}
